package com.cindata

import com.cindata.dictionary.RiskWarningStage
import com.cindata.dictionary.WorkflowType
import grails.converters.JSON
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
@Secured(['isAuthenticated()'])
@Transactional
class TransferBatchController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index() {
        def batchName = params['batchName']
        def startDateStart = params['startDateStart']
        def startDateEnd = params['startDateEnd']
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def sql = ""
        if(batchName){
            sql += " and t.batchName = '${batchName}' "
        }
        if (startDateStart)
        {
            //中文日期转换
            def dates = startDateStart.toString().replaceAll("[^x00-xff]", "-")
            def dates1 = dates.toString().substring(0, dates.length() - 1) + " 00:00:00"
            sql += " and to_char(t.createdDate ,'YYYY-MM-DD HH24:MI:SS') >= '${dates1}' "
        }
        if (startDateEnd)
        {
            //中文日期转换
            def datee = startDateEnd.toString().replaceAll("[^x00-xff]", "-")
            def datee1 = datee.toString().substring(0, datee.length() - 1) + " 23:59:59"
            sql += "  and to_char(t.createdDate,'YYYY-MM-DD HH24:MI:SS') <='${datee1}'  "
        }

        def list = TransferBatch.executeQuery("from TransferBatch t where 1=1 " + sql,[max:max,offset:offset])
        //def count = TransferBatch.count("from TransferBatch t where 1=1 " + sql)
        respond true, model:[list:list,transferBatchCount: 100,params:params]
    }

    def transferList(){
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def sql = pubsql(params)
        def result = RiskWarning.executeQuery("from RiskWarning r where r.stage.name = '已处置'" + sql,[max:max,offset:offset])
        def count  = RiskWarning.executeQuery("select count(1) from RiskWarning r where r.stage.name = '已处置'" + sql)
        respond true, model:[list:result,count:count[0] ,isO:true,params:params],view:"transferList"
    }

    def batchDetail(){
        def batchId = params['batchId']
        def sql = pubsql(params)
        if(batchId){
            sql += " and  r.transferBatch = ${Long.parseLong(batchId)}"
        }
        def result = RiskWarning.executeQuery("from RiskWarning r where 1=1" + sql)
        respond true, model:[list:result,count: result.size(),batchId:batchId,params:params],view:"batchDetail"
    }

    def batchTransfer(){
        def ids = params['ids']
        def accountId = params['accountId']
        def arr = ids.split(",")
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss")
        def account = Account.findById(Long.parseLong(accountId))
        //创建一个batch
        def batch = new TransferBatch()
        batch.batchName ="BL"+sdf.format(new Date())
        batch.processMethod = "转让"
        batch.manageAccount = account
        batch.save(flush:true)
        def stage = RiskWarningStage.findByName("已转让")

        if(!stage){
            def type = WorkflowType.findByName("预警")
            stage =  new RiskWarningStage([name: '已转让', code: '102', type: type])
            stage.save(flush:true)
        }
        arr.each {
           //分给每个riskWarning
            def riskWarning = RiskWarning.findById(Long.parseLong(it))
            riskWarning.transferBatch = batch
            riskWarning.stage = stage
            riskWarning.save()
        }

        println ids
        render([status: "success"] as JSON)
    }

    def pubsql(def params){
        def sql = ""
        def borrowName = params['borrowName']
        def externalId = params['externalId']
        def buildingType = params['buildingType']
        def repayment = params['repayment']
        def riskWarningLevel = params['riskWarningLevel']
        def stage = params['stage']
        def disposalMethod = params['disposalMethod']
        def overdueStart = params['overdueStart']
        def overdueEnd = params['overdueEnd']
        if(borrowName){
            sql += " and r.mortgage.borrName = '${borrowName}'"
        }
        if(externalId){
            sql += " and r.mortgage.externalId = '${externalId}'"
        }
        if(buildingType){
            sql += " and r.mortgage.collateral.estate.buildingType = ${buildingType}"
        }
        if(repayment){
            sql += " and r.mortgage.curRepaymentMode = ${repayment}"
        }
        if(riskWarningLevel){
            sql += " and r.riskWarningLevel = ${riskWarningLevel}"
        }
        if(stage){
            sql += " and r.stage = ${stage}"
        }
        if(disposalMethod){
            sql += " and r.disposalMethod = ${disposalMethod}"
        }
        if (overdueStart)
        {
            sql += " and r.mortgage.curOverdueDuration >= ${overdueStart} "
        }
        if (overdueEnd)
        {
            sql += " and r.mortgage.curOverdueDuration <  ${overdueEnd} "
        }

        return sql
    }


    def show(TransferBatch transferBatch) {
        respond transferBatch
    }

    def create() {
        respond new TransferBatch(params)
    }

    @Transactional
    def save(TransferBatch transferBatch) {
        if (transferBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (transferBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond transferBatch.errors, view:'create'
            return
        }

        transferBatch.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'transferBatch.label', default: 'TransferBatch'), transferBatch.id])
                redirect transferBatch
            }
            '*' { respond transferBatch, [status: CREATED] }
        }
    }

    def edit(TransferBatch transferBatch) {
        respond transferBatch
    }

    @Transactional
    def update(TransferBatch transferBatch) {
        if (transferBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (transferBatch.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond transferBatch.errors, view:'edit'
            return
        }

        transferBatch.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'transferBatch.label', default: 'TransferBatch'), transferBatch.id])
                redirect transferBatch
            }
            '*'{ respond transferBatch, [status: OK] }
        }
    }

    @Transactional
    def delete(TransferBatch transferBatch) {

        if (transferBatch == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        transferBatch.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'transferBatch.label', default: 'TransferBatch'), transferBatch.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'transferBatch.label', default: 'TransferBatch'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }
}
